package com.car.carcontrol;


import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.RequiresApi;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.car.carcontrol.base.BaseActivity;
import com.car.carcontrol.base.BaseApplication;
import com.car.carcontrol.base.BaseViewAdapter;
import com.car.carcontrol.base.BaseViewHolder;
import com.car.carcontrol.util.IntentUtils;
import com.car.carcontrol.util.SharedPreferencesUrls;
import com.car.carcontrol.util.ToastUtil;
import com.monkey.miclockview.MiClockView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

import cn.jock.pickerview.view.view.OptionsPickerView;

//设置
public class SettingActivity extends BaseActivity {

    private FrameLayout v;
    private Activity activity;

    private long loopTime = 60 * 1000;  //时间显示间隔   默认1分钟
    private int cn = 10;     //屏保显示间隔   默认10分钟

    Handler handler = new Handler();

    private MiClockView miClockView;

    Object[] allParam = new Object[]{
            new Object[]{"iv", new Rect(0*width/1280, 0*height/480, 1280*width/1280, 480*height/480), R.drawable.bg, false, new byte[]{0x00,0x01,0x02,0x03,0x04,0x05}},
//            new Object[]{"iv", new Rect(0*width/1280, 0*height/480, 246*width/1280, 477*height/480), R.drawable.bg_left, false, new byte[]{0x00,0x01,0x02,0x03,0x04,0x05}},
//            new Object[]{"iv", new Rect(475*width/1280, 85*height/480, 483*width/1280, 30*height/480), R.drawable.bg_top, false, new byte[]{0x00,0x01,0x02,0x03,0x04,0x05}},


            new Object[]{"hlv", new Rect(20*width/1280, 20*height/480, 1150*width/1280, 100*height/480), "6", 19, Color.BLACK, true, new byte[]{0x00,0x01,0x02,0x03,0x04,0x05}, R.drawable.btn_bcg},

            new Object[]{"tv", new Rect(64*width/1280, 150*height/480, 0, 0), "+", 19, Color.BLACK, true, new byte[]{0x00,0x01,0x02,0x03,0x04,0x05}, R.drawable.btn_bcg},
            new Object[]{"tv", new Rect((64+200*1)*width/1280, 150*height/480, 0, 0), "-", 19, Color.BLACK, true, new byte[]{0x00,0x01,0x02,0x03,0x04,0x05}, R.drawable.btn_bcg},
            new Object[]{"tv", new Rect((64+200*2)*width/1280, 150*height/480, 0, 0), "编辑", 19, Color.BLACK, true, new byte[]{0x00,0x01,0x02,0x03,0x04,0x05}, R.drawable.btn_bcg},

            new Object[]{"mcv", new Rect(0*width/1280, 0*height/480, 1280*width/1280, 480*height/480), "小米时钟", 19, Color.BLACK, R.drawable.clock_bg, R.drawable.needle_second, R.drawable.needle_minute, R.drawable.needle_hour, R.drawable.open},   //界面背景，时钟背景，秒针，分针，时针，圆心

            new Object[]{"iv", new Rect(1220*width/1280, 10*height/480, 46*width/1280, 34*height/480), R.drawable.back_image, true, new byte[]{0x00,0x01,0x02,0x03,0x04,0x05}},

    };

    int id = -1;    //所选界面在水平滚动条中的id
    String name = "";    //所选界面的名字
    TextView tv_add;    //添加按钮
    TextView tv_delete;    //删除按钮
    TextView tv_modify;     //修改按钮


    HashMap<String, Fragment> mapAdd = (HashMap<String, Fragment>)(Config.mapTab.clone());  //map（界面名字，界面类）
    Set<String> setAdd = mapAdd.keySet();   //界面名字集合

    private OptionsPickerView pvOptions;    //添加界面选择器
    private ArrayList<String> item = new ArrayList<>();   //添加界面选择器item界面名字数组

    HorizontalListView hlv; //水平滚动条
    private MyAdapter myAdapter;    //水平滚动条适配器
    private List<WidgetBean> data = new ArrayList<>();    //水平滚动条数据

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        v = new FrameLayout(this);
        setContentView(v);

        context = this;
        activity = this;

        Log.e("sa===onCreate", width+"==="+height+"==="+density);

        initView();

//        loop();
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private void initView(){
        //获取首页当前导航栏item名字集合（用于横向滚动条显示），并获取可添加界面名字集合（用于可添加界面选择器数据）
        for (int i = 0; i < MainActivity.names.length; i++) {
            if(Config.mapTab.containsKey(MainActivity.names[i])){
                setAdd.remove(MainActivity.names[i]);
            }
        }

        Log.e("sa===initView", setAdd.size()+"==="+setAdd);

        pvOptions = new OptionsPickerView(context,false);
        pvOptions.setTitle("可添加界面");

        item = new ArrayList<>(setAdd);
        pvOptions.setPicker(item);
        pvOptions.setCyclic(false, false, false);
        pvOptions.setSelectOptions(0, 0, 0);

        pvOptions.setOnoptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() {

            @Override
            public void onOptionsSelect(int options1, int option2, int options3) {

                Log.e("sa===onOptionsSelect", options1+"==="+item.size());

                if(item.size()>0){
                    Log.e("sa===onOptionsSelect1", options1+"==="+item.get(options1));

                    name = item.get(options1);
                    addFrag();
                }
            }
        });



        for (int i=0; i<allParam.length; i++){
            Object[] obj = (Object[])allParam[i];
            Rect rect = (Rect)obj[1];
            String type = (String)obj[0];

            if("hlv".equals(type)){ //HorizontalListView 加载水平滚动条
                FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(rect.right, rect.bottom);
                params.setMargins(rect.left, rect.top, rect.right, rect.bottom);

                hlv = new HorizontalListView(context);

                List<String> list = Arrays.asList(MainActivity.names);
                ArrayList<String> arrayList = new ArrayList<String>(list);

                for (int j = 0; j < arrayList.size(); j++) {
                    WidgetBean bean = new WidgetBean();
                    bean.setName(arrayList.get(j));
                    data.add(bean);
                }


                myAdapter = new MyAdapter(context);
                myAdapter.setDatas(data);
                hlv.setAdapter(myAdapter);

                v.addView(hlv, params);

                //水平滚动条item点击事件，用于删除和修改界面的第一步
                hlv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long lid) {
                        WidgetBean bean = myAdapter.getDatas().get(position);

                        Log.e("awa===onItemClick", position+"==="+bean.getName()+"==="+view);


                        if(id!=position){
                            if(id!=-1){
                                TextView tv_old = (TextView)hlv.getChildAt(id);
                                tv_old.setBackgroundResource(R.drawable.btn_bcg);
                            }

                            id = position;

                            TextView tv = (TextView)view;
                            tv.setBackgroundResource(R.drawable.btn_bcg2);
                        }

                        name = bean.getName();

                    }
                });

            }else if("tv".equals(type)){
                FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT);
                params.setMargins(rect.left, rect.top, rect.right, rect.bottom);

                String btnName = (String)obj[2];
                int textSize = (int)obj[3];
                int textColor = (int)obj[4];
                int textBcg = (int)obj[7];
                TextView tv = new TextView(context);
                tv.setText(btnName);
                tv.setTextSize(textSize);
                tv.setTextColor(textColor);
                tv.setBackgroundResource(textBcg);
                tv.setPadding(20*width/1280, 10*height/480, 20*width/1280, 10*height/480);
                v.addView(tv, params);

                if("+".equals(btnName)){
                    tv_add = tv;
                }else if("-".equals(btnName)){
                    tv_delete = tv;
                }else if("编辑".equals(btnName)){
                    tv_modify = tv;
                }

                boolean isCanClick = (boolean)obj[5];

                if(isCanClick){
                    tv.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            int textBcg = (int)obj[7];

                            Log.e("sa===tv", btnName+"==="+textBcg);

                            tv_add.setBackgroundResource(R.drawable.btn_bcg);
                            tv_delete.setBackgroundResource(R.drawable.btn_bcg);
                            tv_modify.setBackgroundResource(R.drawable.btn_bcg);

                            if(textBcg==R.drawable.btn_bcg){
                                tv.setBackgroundResource(R.drawable.btn_bcg2);
//                                obj[7] = R.drawable.btn_bcg2;
                            }
//                            else if(textBcg==R.drawable.btn_bcg2){
//                                tv.setBackgroundResource(R.drawable.btn_bcg);
//                                obj[7] = R.drawable.btn_bcg;
//                            }

                            if("+".equals(btnName)){    //点添加

                                Log.e("awa===+", "==="+item.size());

                                pvOptions.show();   //显示界面选择器
                            }else if("-".equals(btnName)){  //点删除
                                if("".equals(name)){
                                    ToastUtil.showMessageApp(context, "请先选择一个界面");
                                }else{
                                    showDialog();
                                }

                            }else if("编辑".equals(btnName)){  //点编辑

                                Log.e("awa===编辑", name+"==="+item.size());

                                if("".equals(name)){
                                    ToastUtil.showMessageApp(context, "请先选择一个界面");
                                }else{
                                    Intent intent = new Intent();
                                    intent.setClass(context, AddWidgetActivity.class);
                                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                    intent.putExtra("name", name);  //传参：界面名字
                                    startActivityForResult(intent, 1);  //调整AddWidgetActivity界面
                                }


                            }

                        }
                    });
                }

            }else if("iv".equals(type)){
                FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(rect.right, rect.bottom);
                params.setMargins(rect.left, rect.top, rect.right, rect.bottom);

                int imgSrc = (int)obj[2];
                ImageView iv = new ImageView(context);
                iv.setImageResource(imgSrc);
                iv.setScaleType(ImageView.ScaleType.FIT_XY);
                v.addView(iv, params);

                boolean isCanClick = (boolean)obj[3];

                if(isCanClick){

                    Log.e("sa===can", imgSrc+"==="+isCanClick);

                    iv.setOnClickListener(new View.OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            int imgId = (int)obj[2];
                            byte[] bytes = (byte[])obj[4];

                            Log.e("sa===iv", imgId+"==="+bytes.length+"==="+bytes);

                            if(imgId==R.drawable.back_image){
                                IntentUtils.startActivity(activity, MainActivity.class);
                                finishMine();
                            }else if(imgId==R.drawable.light){
                                iv.setImageResource(R.drawable.light_0);
                                obj[2] = R.drawable.light_0;
                            }else if(imgId==R.drawable.light_0){
                                iv.setImageResource(R.drawable.light);
                                obj[2] = R.drawable.light;
                            }else if(imgId==R.drawable.light_fw){
                                iv.setImageResource(R.drawable.light_fw_0);
                                obj[2] = R.drawable.light_fw_0;
                            }else if(imgId==R.drawable.light_fw_0){
                                iv.setImageResource(R.drawable.light_fw);
                                obj[2] = R.drawable.light_fw;
                            }

//                            write(bytes);   //TODO
//                            boolean isSendy = uartJnit.getInstance().sendCmds(cmd); //TODO

                        }
                    });
                }

            }else if("mcv".equals(type)){
                FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(rect.right, rect.bottom);
                params.setMargins(rect.left, rect.top, rect.right, rect.bottom);

                int textColor = (int)obj[4];

                miClockView = new MiClockView(context, (int)obj[5], (int)obj[6], (int)obj[7], (int)obj[8], (int)obj[9]);
                miClockView.setBackgroundColor(textColor);

                v.addView(miClockView, params);

                miClockView.setVisibility(View.GONE);

                miClockView.setOnTouchListener(new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        Log.e("mcv===onTouch", "===");

                        miClockView.setVisibility(View.GONE);
                        return false;
                    }
                });

            }
        }
    }

    //显示对话框：提示是否删除所选界面
    void showDialog(){
        CustomDialog.Builder customBuilder = new CustomDialog.Builder(context);
        customBuilder.setTitle("温馨提示").setMessage("是否删除?")
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();

                    }
                }).setPositiveButton("确认", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();

                Log.e("sa===showDialog", "===");

                deleteFrag();
            }
        });
        customBuilder.create().show();
    }

    //跳转添加界面
    private void addFrag(){
        Log.e("sa===addFrag", name+"===");

        Intent intent = new Intent();
        intent.setClass(context, AddWidgetActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("name", name);
        startActivityForResult(intent, 1);
    }

    //删除所选界面并刷新数据、选择器
    private void deleteFrag(){
        Log.e("awa===deleteFrag", name+"==="+id);

        //数组转list
        List<String> list = Arrays.asList(MainActivity.names);
        ArrayList<String> arrayList = new ArrayList<String>(list);

        Log.e("arrayList===1", arrayList.size()+"==="+arrayList+"==="+name+"==="+MainActivity.names);

        arrayList.remove(name); //刷新数据

        Log.e("arrayList===2", arrayList.size()+"==="+arrayList+"==="+name+"==="+MainActivity.names);

        MainActivity.names = arrayList.toArray(new String[0]);

        Log.e("arrayList===3", arrayList.size()+"==="+arrayList+"==="+name+"==="+MainActivity.names);

        SharedPreferencesUrls.getInstance().putObject("names", arrayList.toArray(new String[0]));   //更新后的导航栏item名字数组存在手机内部存储器

        SharedPreferencesUrls.getInstance().remove(Config.mapSp.get(name)); //刷新数据

        m_myHandler.sendEmptyMessage(0);    //刷新选择器
    }

    private void loop(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                long n=0;

                while (true){

//                    m_myHandler.sendEmptyMessage(1);

                    try {
                        Thread.sleep(loopTime);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    n++;

                    if(n%cn==0){
                        m_myHandler.sendEmptyMessage(2);
                    }

                }

            }
        }).start();
    }

    protected Handler m_myHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message mes) {
            switch (mes.what) {
                case 0:
                    item.add(name);
//                    pvOptions.setPicker(item);
//                    pvOptions.setCyclic(false, false, false);
//                    pvOptions.setSelectOptions(0, 0, 0);

                    pvOptions = new OptionsPickerView(context,false);
                    pvOptions.setTitle("可添加界面");

                    pvOptions.setPicker(item);
                    pvOptions.setCyclic(false, false, false);
                    pvOptions.setSelectOptions(0, 0, 0);

                    pvOptions.setOnoptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() {

                        @Override
                        public void onOptionsSelect(int options1, int option2, int options3) {

                            Log.e("sa===onOptionsSelect", options1+"==="+item.size());

                            if(item.size()>0){
                                Log.e("sa===onOptionsSelect1", options1+"==="+item.get(options1));

                                name = item.get(options1);
                                addFrag();
                            }
                        }
                    });


                    Log.e("item===", item.size()+"==="+item+"==="+name+"==="+id);

                    data.remove(id);
                    myAdapter.notifyDataSetChanged();

                    Toast.makeText(context, "删除成功!", Toast.LENGTH_SHORT).show();
                    break;

                case 1:

                    //获取当前时间
//                    Date date = new Date(System.currentTimeMillis());
//                    String time1 = simpleDateFormat.format(date);
//                    String time2 = simpleDateFormat2.format(date);
//
//
//                    Log.e("m_myHandler===1", "==="+bytes_temp);
//
//                    tv_temp.setText("25℃");
////                    read(bytes_temp);     //TODO
//                    tv_time.setText(time1);
//                    tv_date.setText(time2);

                    break;

                case 2:
                    miClockView.setVisibility(View.VISIBLE);
                    break;

                default:
                    break;
            }
            return false;
        }
    });


    private class MyAdapter extends BaseViewAdapter<WidgetBean> {

        private LayoutInflater inflater;

        public MyAdapter(Context context){
            super(context);
            this.inflater = LayoutInflater.from(context);
        }



        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (null == convertView) {
                convertView = inflater.inflate(R.layout.item_cur_frag, null);
            }

            TextView tv_name = BaseViewHolder.get(convertView, R.id.item_name);

            WidgetBean bean = getDatas().get(position);

//            Log.e("awa===getView", hlv.mCurrentX+"==="+hlv.mScroller+"==="+hlv.mScroller.getCurrX()+"==="+hlv.getX()+"==="+hlv.getY()+"==="+hlv.getScrollY()+"==="+hlv.getScrollX()+"==="+hlv.getFirstVisiblePosition()+"==="+bean.getName()+"===");

            tv_name.setText(bean.getName());

            return convertView;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        Log.e("onKeyDown===", "==="+keyCode);

        if (keyCode == KeyEvent.KEYCODE_BACK) {

            IntentUtils.startActivity(activity, MainActivity.class);
            finishMine();

            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    //添加成功后返回并刷新数据、界面选择器
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent idata) {

        Log.e("sa===onActivityResult", requestCode+"==="+resultCode);

        switch (requestCode) {
            case 1:
                if (resultCode == RESULT_OK) {

                    WidgetBean bean = new WidgetBean();
                    bean.setName(name);
                    data.add(bean);
                    myAdapter.notifyDataSetChanged();

                    item.remove(name);
//                    pvOptions.setPicker(item);

                    pvOptions = new OptionsPickerView(context,false);
                    pvOptions.setTitle("可添加界面");

                    pvOptions.setPicker(item);
                    pvOptions.setCyclic(false, false, false);
                    pvOptions.setSelectOptions(0, 0, 0);

                    pvOptions.setOnoptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() {

                        @Override
                        public void onOptionsSelect(int options1, int option2, int options3) {

                            Log.e("sa===onOptionsSelect", options1+"==="+item.size());

                            if(item.size()>0){
                                Log.e("sa===onOptionsSelect1", options1+"==="+item.get(options1));

                                name = item.get(options1);
                                addFrag();
                            }
                        }
                    });

                    Toast.makeText(context, "添加成功!", Toast.LENGTH_SHORT).show();

                } else {
                }
                break;
        }

        super.onActivityResult(requestCode, resultCode, idata);
    }
}
